package com.study.samsung.Control;

import com.alibaba.fastjson.JSONObject;
import com.study.samsung.Entity.User;
import com.study.samsung.Service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    UserService us = new UserService();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/WEB-INF/jsp/login.jsp")
                .forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("utf-8");
            String account =req.getParameter("account");
            String pwd = req.getParameter("pwd");
        PrintWriter writer = resp.getWriter();

        User user = new User();
        user.setAccount(account);
        user.setUpwd(pwd);
        System.out.println(user.toString());

        Integer result = us.login(user);
        System.out.println("登录的用户信息："+user);
        if (result>0){
            HttpSession session =req.getSession();
            Object[] objects = new Object[2];
            objects[0]=1;
            if (session.getAttribute("resetImg")=="已重置"){
                objects[1]="已重置";
            }else {
                objects[1]="未重置";
            }
            JSONObject jsonObject = new JSONObject();
            jsonObject.toJSONString(objects);
            session.setAttribute("user",user);
            writer.print(1);
        }else {
            writer.print(result);
        }
        System.out.println(result);
        writer.close();
    }
}
